package gui;

import java.awt.Color;
import java.awt.ComponentOrientation;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Point;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.border.SoftBevelBorder;

import Classes.Clients;
import Classes.Usuarios;

public class LoginWindow extends JFrame{
	private static final long serialVersionUID = 1L;
	/* My Variables */
	private boolean hasUsername = false;
	private boolean hasPassword = false;
	private int conttries = 0;
	private Usuarios Me = null;
	
	private JFrame jFMainWindow = null;  //  @jve:decl-index=0:visual-constraint="41,35"
	private JPanel jCPWindowLogin = null;
	private JTextField jTFUsername = null;  //  @jve:decl-index=0:visual-constraint="346,108"
	private JLabel jLUsername = null;  //  @jve:decl-index=0:visual-constraint="476,112"
	private JLabel jLTitle = null;  //  @jve:decl-index=0:visual-constraint="402,92"
	private JLabel jLPassword = null;  //  @jve:decl-index=0:visual-constraint="754,114"
	private JPasswordField jPFPassword = null;  //  @jve:decl-index=0:visual-constraint="754,170"
	private JButton jBConnect = null;  //  @jve:decl-index=0:visual-constraint="754,222"
	private JButton jBExit = null;  //  @jve:decl-index=0:visual-constraint="759,267"
	private JLabel jLPicture = null;  //  @jve:decl-index=0:visual-constraint="754,250"
	
	/* BEGIN: My Getters and Setters */
	
	public int getConttries(){
		return this.conttries;
	}
	
	public void setConttries(int value){
		this.conttries = value;
	}
	

	/* END: of My Getters and Setters */
	
	/*******************************************/
	
	/* BEGIN: My Transactional Actions */
	public void incConttries(){
		this.conttries++;
	}
	
	public void doLogin(){
		String user = new String(getJTFUsername().getText().trim());
		String pass = new String(getJPFPassword().getText().trim());
		Usuarios Eu = new Usuarios(user,pass,false);
		//TODO
		//ATENCAO: ESSE IP EH FIXO PARA TESTE, APENAS
		Eu.setIP("192.168.1.100");
	
		if ( Clients.doLogin(Eu) ){
			ArrayList<Usuarios> users = Clients.getUsersRegistereds();
			for (Usuarios usuario : users) {
				if(usuario.getNome().equals(Eu.getNome())){
					Eu.setUDPport(usuario.getUDPport());
					break;
				}
			}
			setMe(Eu);
			System.out.println("Connection successfully established.");
			try {
				MainWindow mw = new MainWindow(this, users, Me);
				Thread tmw = new Thread(mw);
				this.setConttries(0);
				this.setVisible(false);
				tmw.start();
				tmw.join();
			} catch (InterruptedException e) {
				System.out.println("Exception = " + e.getMessage());
			} catch (Exception e){
				System.out.println("Exception = " + e.getMessage());
			}
			
		}else{
			this.incConttries();
			String message = "You aren't able to do login, something is wrong!" +
							"\nPlease verify your username and/or password."+
							 "\nBecause you have tried to connect " + this.getConttries() + " times already!";
			System.err.println(message);
			JOptionPane.showMessageDialog(this, message, "Something isn't right.", JOptionPane.ERROR_MESSAGE);
			
		}
		
	}
	
	public Usuarios getMe() {
		return Me;
	}

	public void setMe(Usuarios me) {
		Me = me;
	}

	public void doExit(){
		int state = JOptionPane.showConfirmDialog(this, "Do you really want to leave?",
				"EXIT...", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
		
		if (state == JOptionPane.YES_OPTION){
				System.out.println("\n ***** Goodbye =D *****\n");
				System.exit(0);
		}
		else
			return;
	}
	
	/* END: My Transactional Actions */
	
	public LoginWindow() {
		super();
		initialize();
	}
	
	private void initialize() {
		this.setSize(300, 400);
		this.setMaximumSize(new Dimension(300,400));
		this.setMinimumSize(new Dimension(300,400));
		this.setResizable(false);
		this.setContentPane(getJCPWindowLogin());
		this.setTitle("BeH Communicator V1.1 Alpha");
		this.setLocation(550, 250); //Posicao da Janela Arrumar.
		this.setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
		this.addWindowListener(new java.awt.event.WindowAdapter() {
			public void windowClosing(java.awt.event.WindowEvent e) {
				doExit();
			}
		});
	}
	
	/**
	 * This method initializes jFMainWindow	
	 * 	
	 * @return javax.swing.JFrame	
	 */
	private JFrame getJFMainWindow() {
		if (jFMainWindow == null) {
			jFMainWindow = new JFrame();
			jFMainWindow.setSize(new Dimension(300, 400));
			jFMainWindow.setContentPane(getJCPWindowLogin());
			jFMainWindow.setDefaultCloseOperation(this.DO_NOTHING_ON_CLOSE);  
			jFMainWindow.addWindowListener(new WindowAdapter() {  
		         public void windowClosing(WindowEvent e) {  
		             doExit();
		         }  
		      });  
			
		}
		return jFMainWindow;
	}

	/**
	 * This method initializes jCPWindowLogin	
	 * 	
	 * @return javax.swing.JPanel	
	 */
	private JPanel getJCPWindowLogin() {
		if (jCPWindowLogin == null) {
			jCPWindowLogin = new JPanel();
			jCPWindowLogin.setLayout(null);
			jCPWindowLogin.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
			jCPWindowLogin.setBorder(new SoftBevelBorder(SoftBevelBorder.RAISED));
			jCPWindowLogin.add(getJTFUsername());
			jCPWindowLogin.add(getJLUsername());
			jCPWindowLogin.add(getJLTitle());
			jCPWindowLogin.add(getJBConnect());
			jCPWindowLogin.add(getJBExit());
			jCPWindowLogin.add(getJPFPassword());
			jCPWindowLogin.add(getJLPassword());
			jCPWindowLogin.add(getJLPicture());
			
		}
		return jCPWindowLogin;
	}

	/**
	 * This method initializes jTFUsername	
	 * 	
	 * @return javax.swing.JTextField	
	 */
	private JTextField getJTFUsername() {
		if (jTFUsername == null) {
			jTFUsername = new JTextField();
			jTFUsername.setSize(new Dimension(170, 30));
			jTFUsername.setLocation(new Point(101, 77));
			jTFUsername.setHorizontalAlignment(JTextField.CENTER);
			jTFUsername.setFont(new Font("Verdana", Font.BOLD, 12));
			jTFUsername.setToolTipText("Maximum lenght Size for USERNAMEs are 20.");
			jTFUsername.addKeyListener(new java.awt.event.KeyAdapter() {
				public void keyTyped(java.awt.event.KeyEvent e) {
					if ( !getJTFUsername().getText().trim().equals("")){
						hasUsername = true;
					} else {
						hasUsername = false;
					}
					
					if ( hasPassword && hasUsername )
						getJBConnect().setEnabled(true);
					else
						getJBConnect().setEnabled(false);
					
					if ( getJTFUsername().getText().trim().length() >= 20 ){
						getJTFUsername().setText(getJTFUsername().getText().trim().substring(0, 19));
					}
					
				}
			});
		}
		return jTFUsername;
	}

	/**
	 * This method initializes jLUsername	
	 * 	
	 * @return javax.swing.JLabel	
	 */
	private JLabel getJLUsername() {
		if (jLUsername == null) {
			jLUsername = new JLabel();
			jLUsername.setText("Username :");
			jLUsername.setLocation(new Point(14, 77));
			jLUsername.setDisplayedMnemonic(KeyEvent.VK_UNDEFINED);
			jLUsername.setHorizontalAlignment(SwingConstants.CENTER);
			jLUsername.setHorizontalTextPosition(SwingConstants.CENTER);
			jLUsername.setSize(new Dimension(81, 27));
		}
		return jLUsername;
	}

	/**
	 * This method initializes jLTitle	
	 * 	
	 * @return javax.swing.JLabel	
	 */
	private JLabel getJLTitle() {
		if (jLTitle == null) {
			jLTitle = new JLabel();
			jLTitle.setText("Burg & Sene Communicator!");
			jLTitle.setLocation(new Point(15, 21));
			jLTitle.setHorizontalTextPosition(SwingConstants.CENTER);
			jLTitle.setHorizontalAlignment(SwingConstants.CENTER);
			jLTitle.setFont(new Font("Comic Sans MS", Font.BOLD, 18));
			jLTitle.setBackground(new Color(119, 255, 0));
			jLTitle.setSize(new Dimension(263, 32));
		}
		return jLTitle;
	}

	/**
	 * This method initializes jLPassword	
	 * 	
	 * @return javax.swing.JLabel	
	 */
	private JLabel getJLPassword() {
		if (jLPassword == null) {
			jLPassword = new JLabel();
			jLPassword.setText("Password :");
			jLPassword.setLocation(new Point(15, 131));
			jLPassword.setHorizontalAlignment(SwingConstants.CENTER);
			jLPassword.setHorizontalTextPosition(SwingConstants.CENTER);
			jLPassword.setSize(new Dimension(80, 27));
		}
		return jLPassword;
	}

	/**
	 * This method initializes jPFPassword	
	 * 	
	 * @return javax.swing.JPasswordField	
	 */
	private JPasswordField getJPFPassword() {
		if (jPFPassword == null) {
			jPFPassword = new JPasswordField();
			jPFPassword.setSize(new Dimension(170, 29));
			jPFPassword.setFont(new Font("Dialog", Font.PLAIN, 12));
			jPFPassword.setForeground(new Color(255, 119, 0));
			jPFPassword.setLocation(new Point(102, 129));
			jPFPassword.setHorizontalAlignment(JTextField.CENTER);
			jPFPassword.setToolTipText("Maximum lenght Size for PASSWORDs are 15.");
			jPFPassword.addKeyListener(new java.awt.event.KeyAdapter() {
				public void keyTyped(java.awt.event.KeyEvent e) {
					if ( !getJPFPassword().getText().trim().equals("")){
						hasPassword = true;
					} else {
						hasPassword = false;
					}
					
					if ( hasPassword && hasUsername )
						getJBConnect().setEnabled(true);
					else
						getJBConnect().setEnabled(false);
					
					if ( getJPFPassword().getText().trim().length() >= 15 ){
						getJPFPassword().setText(getJPFPassword().getText().trim().substring(0, 14));
					}
				}
			});
		}
		return jPFPassword;
	}

	/**
	 * This method initializes jBConnect	
	 * 	
	 * @return javax.swing.JButton	
	 */
	private JButton getJBConnect() {
		if (jBConnect == null) {
			jBConnect = new JButton();
			jBConnect.setSize(new Dimension(103, 26));
			jBConnect.setLocation(new Point(32, 318));
			jBConnect.setEnabled(false);
			jBConnect.setMnemonic(KeyEvent.VK_C);
			jBConnect.setText("Connect");
			jBConnect.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					doLogin();
				}
			});
		}
		return jBConnect;
	}

	/**
	 * This method initializes jBExit	
	 * 	
	 * @return javax.swing.JButton	
	 */
	private JButton getJBExit() {
		if (jBExit == null) {
			jBExit = new JButton();
			jBExit.setSize(new Dimension(93, 27));
			jBExit.setLocation(new Point(167, 318));
			jBExit.setMnemonic(KeyEvent.VK_E);
			jBExit.setActionCommand("Exit");
			jBExit.setText("Exit");
			jBExit.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					doExit();
				}
			});
		}
		return jBExit;
	}

	/**
	 * This method initializes jLPicture	
	 * 	
	 * @return javax.swing.JLabel	
	 */
	private JLabel getJLPicture() {
		if (jLPicture == null) {
			jLPicture = new JLabel();
			jLPicture.setText("");	
			jLPicture.setLocation(new Point(74, 183));
			jLPicture.setIcon(new ImageIcon("img/img1.gif"));
			jLPicture.setSize(new Dimension(jLPicture.getIcon().getIconWidth(), 
											jLPicture.getIcon().getIconHeight()));
		}
		return jLPicture;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
		LoginWindow lw = new LoginWindow();
		//lw.setDefaultCloseOperation(EXIT_ON_CLOSE);
		lw.setVisible(true);

	}

}  //  @jve:decl-index=0:visual-constraint="414,35"
